import { forEachFormOptions, isNumberType } from '@/utils/formMakeUtils.js';
import { formulaChange, quoteRemoveTag } from '@/views/legal/process/components/formMake/utils/index.js';
import { EventBus } from '@/utils/eventBus';
import { ROLE_TYPE } from '@/utils/const/process';
import { mapState } from 'vuex';
export default {
  computed: {
    ...mapState({
      'allUserFields': state => state.formMake.allUserFields,
      'BPList': state => state.formMake.BPList,
      'allDeptFields': state => state.formMake.allDeptFields
    })
  },
  created() {
    EventBus.$on('formOptionsChange', data => {
      const allowTypes = ['changeName', 'add', 'remove', 'subtable-add', 'subtable-remove'];
      if (allowTypes.includes(data.type)) {
        this.handelChange(data);
      }
      // 节点删除或添加时改变 keyToFormula
      if (data.type === 'remove' || data.type === 'subtable-remove') {
        if ((data.data.type === 'linkForm' || data.data.type === 'subform') && data.data.subform) {
          data.data.subform.forEach(j => {
            formulaChange('remove', this.formOptions, data.data, `${data.data.type}*${data.data.key}*${j.key}`);
          });
        } else {
          formulaChange('remove', this.formOptions, data.data);
        }
        if (data.data.type === 'grid' || data.data.type === 'subform') {
          this.initAllWidget();
        }
        if (data.data.type === 'formulaInput') {
          this.deleteFormulaInput(data);
        }
      } else if (data.type === 'add' || data.type === 'subtable-add') {
        if ((data.data.type === 'grid' || data.data.type === 'subform') && data.isClone) {
          this.initAllWidget();
        } else if (data.data.type === 'formulaInput' && data.data.options.formulaOrigin.length > 0) {
          this.initKeyToFormula();
        }
      }
    });
    EventBus.$on('changeLinkForm', data => {
      this.changeLinkForm(data);
    });
  },
  methods: {
    handelChange(data) {
      if (!this.$store) return;
      const type = data.type;
      const element = _.cloneDeep(data.data);
      let storeType = '';
      if (element.type === 'user') {
        storeType = 'user';
      } else if (isNumberType(element)) {
        storeType = 'number';
      } else if (element.type === 'subform') { // 子表单
        storeType = 'subform';
      } else if (element.type === 'linkForm') { // 关联表单
        storeType = 'linkForm';
      }
      if (storeType) {
        if (type === 'add' || type === 'subtable-add') {
          this.$store.dispatch('addWidget', { type: storeType, widget: element });
        } else if (type === 'remove' || type === 'subtable-remove') {
          this.$store.dispatch('removeWidget', { type: storeType, widget: element });
        } else if (type === 'changeName') {
          this.$store.dispatch('changeNameWidget', { type: storeType, widget: element });
        }
      }
      if (type === 'subtable-add' || type === 'subtable-remove') {
        this.$store.dispatch('changeSubform', { type: type, widget: element, formOptions: this.formOptions });
      }
    },
    changeLinkForm(element) {
      if (!this.$store) return;
      this.$store.dispatch('changeLinkForm', { type: 'change', widget: element });
    },
    /**
     * 字段分类收集
     */
    // 初始化所有字段的分类
    initAllWidget() {
      const list = this.formOptions && this.formOptions.list;
      if (!list || list.length === 0) {
        this.$store.dispatch('initAllWidget', null);
        return;
      }
      const ans = {
        user: [], // 表单的所有用户字段
        number: [], // 表单的所有数值字段
        subform: [],
        linkForm: [] // 关联字段
      };
      const keyToFormula = {};
      forEachFormOptions(list, (element, subformKey) => {
        if (element.type === 'input') {
          // 处理旧数据
          if (!element.options.options) this.$set(element.options, 'options', []);
          if (element.options.isCanEdit === undefined) this.$set(element.options, 'isCanEdit', false);
          if (element.options.defaultType === undefined) this.$set(element.options, 'defaultType', 0);
          if (!element.options.numberRange) this.$set(element.options, 'numberRange', [-99999999999, 99999999999]);
          if (element.options.precision === undefined) this.$set(element.options, 'precision', 2);
          if (!element.options.isShowPercentage) this.$set(element.options, 'isShowPercentage', false);
        }
        if (element.type === 'subform') {
          if (element.options.isCard === undefined) this.$set(element.options, 'isCard', false);
        }
        if (subformKey) { // 如果是子表单里面的字段，则补充其所在子表单的key
          element.linkFormKey = subformKey;
        }
        if (element.type === 'formulaInput' && element.options.formulaOrigin) {
          this.setKeyToFormula(element, keyToFormula);
        }
        if (element.type === 'title') { // 处理旧数据
          if (!element.options) this.$set(element, 'options', { titleLevel: 1 });
        }
        if (element.type === 'user') {
          ans.user.push(_.cloneDeep(element));
        } else if (isNumberType(element)) {
          ans.number.push(_.cloneDeep(element));
        } else if (element.type === 'subform') { // 子表单
          ans.subform.push(element);
        } else if (element.type === 'linkForm') {
          if (element.subform) {
            element.subform.forEach(i => {
              i.linkFormKey = element.key;
              i.isLinkField = true;
            });
          }
          ans.linkForm.push(element);
        }
      });
      this.formOptions.config.keyToFormula = keyToFormula;
      this.$store.dispatch('initAllWidget', ans);
    },
    deleteFormulaInput(data) {
      const element = data.data;
      if (element.options.formulaOrigin) {
        element.options.formulaOrigin.forEach(el => {
          if (el !== 'math' && el !== 'number') {
            quoteRemoveTag(el, this.formOptions && this.formOptions.config.keyToFormula || {}, data.data);
          }
        });
      }
    },
    setKeyToFormula(element, keyToFormula) {
      if (element.type === 'formulaInput' && element.options.formulaOrigin && !element.options.modeType) {
        element.options.formulaOrigin.forEach(i => {
          if (i.type !== 'number' && i.type !== 'math') {
            let key = i.key;
            if (i.linkFormKey && i.isLinkField) {
              key = `linkForm*${i.linkFormKey}*${i.key}`;
            } else if (i.linkFormKey && i.isSubTable) {
              key = `subform*${i.linkFormKey}*${i.key}`;
            }
            if (!keyToFormula[key]) keyToFormula[key] = [];
            keyToFormula[key].push(element.key);
          }
        });
      }
    },
    initKeyToFormula() {
      const keyToFormula = {};
      forEachFormOptions(this.formOptions.list, (element) => {
        if (element.type === 'formulaInput' && element.options.formulaOrigin) {
          this.setKeyToFormula(element, keyToFormula);
        }
      });
      this.formOptions.config.keyToFormula = keyToFormula;
    },
    // 清除角色选中项中表单已删除的人员选择组件
    clearDeletedData(list) {
      list.forEach(item => {
        if (item.roleType === ROLE_TYPE.DESIGNATE) {
          const hasFields = this.allUserFields.some(userField => userField.key === item.designateUserSelect);
          !hasFields && (item.designateUserSelect = '');
        } else if (item.roleType === ROLE_TYPE.BP_APPROVER) {
          if (Array.isArray(item.bpDepts) && item.bpDepts.length) {
            item.bpDepts = item.bpDepts.filter(key => this.allDeptFields.some(deptField => deptField.key === key));
          }
          if (Array.isArray(item.bpNames) && item.bpNames.length) {
            item.bpNames = item.bpNames.filter(name => this.BPList.some(BP => BP.name === name));
          }
        } else if (item.roleType === ROLE_TYPE.DESIGNATE_DIRECTOR) {
          if (item.designateDirectorUser && !this.allUserFields.filter(userField => userField.key === item.designateDirectorUser).length) {
            item.designateDirectorUser = '';
            item.designateDirector = '';
          }
        }
      });
      return list;
    }
  }
};
